using LiJ.Common.Core;
using LiJ.Common.Extention;
using LiJ.Http.Mos;
using LiJ.Framework.Official.Agent.Mos;
using System.Text;
using System.Threading.Tasks;

namespace LiJ.Framework.Official.Agent
{
	/// <summary>
	///  第三方代理平台授权接口
	/// </summary>
	public class WxAgentAuthApi : WxAgentBaseApi
	{
		/// <summary>
		///  构造函数
		///     注意配置信息是 第三方相关的配置信息
		/// </summary>
		/// <param name="config">第三方代理的配置信息（上下文也需要设置代理相关的配置信息）</param>
		public WxAgentAuthApi(AppConfig config = null)
			: base(config)
		{
		}

		/// <summary>
		///  获取预授权码pre_auth_code
		/// </summary>
		/// <returns></returns>
		private async Task<WxGetPreAuthCodeResp> GetPreAuthCode()
		{
			LHttpRequest req = new LHttpRequest
			{
				AddressUrl = string.Format("{0}/cgi-bin/component/api_create_preauthcode", "https://api.weixin.qq.com"),
				HttpMothed = HttpMothed.Post,
				CustomBody = string.Format("{{\"component_appid\":\"{0}\"}}", base.ApiConfig.AppId)
			};
			return await base.RestCommonAgentAsync<WxGetPreAuthCodeResp>(req, null);
		}

		/// <summary>
		/// 获取公众号/小程序授权地址
		/// </summary>
		/// <param name="redirectUrl">回调地址</param>
		/// <returns></returns>
		public async Task<ResultMo<string>> GetPreAuthUrl(string redirectUrl)
		{
			WxGetPreAuthCodeResp wxGetPreAuthCodeResp = await this.GetPreAuthCode();
			if (!wxGetPreAuthCodeResp.IsSuccess())
			{
				return wxGetPreAuthCodeResp.ConvertToResultOnly<string>();
			}
			if (redirectUrl.Contains("://"))
			{
				redirectUrl = redirectUrl.UrlEncode();
			}
			return new ResultMo<string>(string.Format("https://mp.weixin.qq.com/cgi-bin/componentloginpage?component_appid={0}&pre_auth_code={1}&redirect_uri={2}", base.ApiConfig.AppId, wxGetPreAuthCodeResp.pre_auth_code, redirectUrl));
		}

		/// <summary>
		/// 获取平台下当前授权账号的AccessToken响应实体
		/// </summary>
		/// <param name="authorizationCode">授权code,会在授权成功时返回给第三方平台</param>
		/// <returns></returns>
		public async Task<WxGetGrantedAccessTokenResp> GetGrantorAccessToken(string authorizationCode)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\"component_appid\":\"").Append(base.ApiConfig.AppId).Append("\",");
			stringBuilder.Append("\"authorization_code\":\"").Append(authorizationCode).Append("\" }");
			LHttpRequest req = new LHttpRequest
			{
				AddressUrl = string.Format("{0}/cgi-bin/component/api_query_auth", "https://api.weixin.qq.com"),
				HttpMothed = HttpMothed.Post,
				CustomBody = stringBuilder.ToString()
			};
			return await base.RestCommonAgentAsync<WxGetGrantedAccessTokenResp>(req, null);
		}

		/// <summary>
		/// 获取平台下当前授权账号的AccessToken响应实体
		/// </summary>
		/// <param name="grantorRefreshToken">授权者的刷新Token</param>
		/// <param name="grantorAppId">授权者的Appid</param>
		/// <returns></returns>
		public async Task<WxRefreshGrantedAccessTokenResp> RefreshGrantorAccessToken(string grantorAppId, string grantorRefreshToken)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\"component_appid\":\"").Append(base.ApiConfig.AppId).Append("\",");
			stringBuilder.Append("\"authorizer_appid\":\"").Append(grantorAppId).Append("\",");
			stringBuilder.Append("\"authorizer_refresh_token\":\"").Append(grantorRefreshToken).Append("\" }");
			LHttpRequest req = new LHttpRequest
			{
				AddressUrl = string.Format("{0}/cgi-bin/component/api_authorizer_token", "https://api.weixin.qq.com"),
				HttpMothed = HttpMothed.Post,
				CustomBody = stringBuilder.ToString()
			};
			return await base.RestCommonAgentAsync<WxRefreshGrantedAccessTokenResp>(req, null);
		}

		/// <summary>
		///  获取公号的授权（账号+权限）信息
		/// </summary>
		/// <param name="grantorAppId"></param>
		/// <returns></returns>
		public async Task<WxGetGrantorInfoResp> GetGrantorInfo(string grantorAppId)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\"component_appid\":\"").Append(base.ApiConfig.AppId).Append("\",");
			stringBuilder.Append("\"authorizer_appid\":\"").Append(grantorAppId).Append("\"}");
			LHttpRequest req = new LHttpRequest
			{
				AddressUrl = string.Format("{0}/cgi-bin/component/api_get_authorizer_info", "https://api.weixin.qq.com"),
				HttpMothed = HttpMothed.Post,
				CustomBody = stringBuilder.ToString()
			};
			return await base.RestCommonAgentAsync<WxGetGrantorInfoResp>(req, null);
		}

		/// <summary>
		///  获取授权方的选项设置信息
		/// location_report(地理位置上报选项)	0-无上报 1-进入会话时上报 2-每5s上报
		/// voice_recognize（语音识别开关选项）	0-关闭语音识别 1-开启语音识别
		/// customer_service（多客服开关选项）	0-关闭多客服 1-开启多客服
		/// </summary>
		/// <param name="grantorAppId">授权公众号或小程序的appid</param>
		/// <param name="optionName">选项名称</param>
		/// <returns></returns>
		public async Task<WxGetGrantorOptionResp> GetGrantorOption(string grantorAppId, string optionName)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\"component_appid\":\"").Append(base.ApiConfig.AppId).Append("\",");
			stringBuilder.Append("\"authorizer_appid\":\"").Append(grantorAppId).Append("\",");
			stringBuilder.Append("\"option_name\":\"").Append(optionName).Append("\"}");
			LHttpRequest req = new LHttpRequest
			{
				AddressUrl = string.Format("{0}/cgi-bin/component/api_get_authorizer_option", "https://api.weixin.qq.com"),
				HttpMothed = HttpMothed.Post,
				CustomBody = stringBuilder.ToString()
			};
			return await base.RestCommonAgentAsync<WxGetGrantorOptionResp>(req, null);
		}

		/// <summary>
		///  设置授权方的选项信息
		/// location_report(地理位置上报选项)	0-无上报 1-进入会话时上报 2-每5s上报
		/// voice_recognize（语音识别开关选项）	0-关闭语音识别 1-开启语音识别
		/// customer_service（多客服开关选项）	0-关闭多客服 1-开启多客服
		/// </summary>
		/// <param name="grantorAppId">授权公众号或小程序的appid</param>
		/// <param name="optionName">选项名称</param>
		/// <param name="optionValue">设置的选项值</param>
		/// <returns></returns>
		public async Task<WxBaseResp> SetGrantorOption(string grantorAppId, string optionName, string optionValue)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\"component_appid\":\"").Append(base.ApiConfig.AppId).Append("\",");
			stringBuilder.Append("\"authorizer_appid\":\"").Append(grantorAppId).Append("\",");
			stringBuilder.Append("\"option_name\":\"").Append(optionName).Append("\",");
			stringBuilder.Append("\"option_value\":\"").Append(optionValue).Append("\"}");
			LHttpRequest req = new LHttpRequest
			{
				AddressUrl = string.Format("{0}/cgi-bin/component/api_set_authorizer_option", "https://api.weixin.qq.com"),
				HttpMothed = HttpMothed.Post,
				CustomBody = stringBuilder.ToString()
			};
			return await base.RestCommonAgentAsync<WxBaseResp>(req, null);
		}

		/// <summary>
		///  获取授权者列表
		/// </summary>
		/// <param name="grantorAppId"></param>
		/// <param name="offset"></param>
		/// <param name="count"></param>
		/// <returns></returns>
		public async Task<WxGetGrantorListResp> GetGrantorList(string grantorAppId, int offset, int count)
		{
			StringBuilder stringBuilder = new StringBuilder();
			stringBuilder.Append("{\"component_appid\":\"").Append(base.ApiConfig.AppId).Append("\",");
			stringBuilder.Append("\"offset\":\"").Append(offset).Append("\",");
			stringBuilder.Append("\"count\":\"").Append(count).Append("\"}");
			LHttpRequest req = new LHttpRequest
			{
				AddressUrl = string.Format("{0}/cgi-bin/component/api_get_authorizer_list", "https://api.weixin.qq.com"),
				HttpMothed = HttpMothed.Post,
				CustomBody = stringBuilder.ToString()
			};
			return await base.RestCommonAgentAsync<WxGetGrantorListResp>(req, null);
		}
	}
}
